package com.example.demo.controller;

import com.example.demo.commom.AjaxResult;
import com.example.demo.commom.JwtUtils;
import com.example.demo.commom.Password;
import com.example.demo.model.dto.user.RegDto;
import com.example.demo.model.entity.Userinfo;
import com.example.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2024-04-22
 * Time:14:34
 *
 * 语义是提交数据的，都用 Post
 * 凡是 Post 请求，都使用对象来接收(对象前面必须要有 @RequestBody)
 * 凡是 Get 请求，都是使用 零散参数 接收(没要求)
 *
 */
//@Controller
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //注册
    @PostMapping("/reg")
    public AjaxResult reg(@RequestBody RegDto regDto){
        //参数校验
        if(!StringUtils.hasLength(regDto.getUsername()) || !StringUtils.hasLength(regDto.getPassword())){
            return AjaxResult.fail(1001);
        }
        //检查用户名是否被注册过
        Userinfo userinfo = userService.getUserinfo(regDto.getUsername());
        if(userinfo != null){
            return  AjaxResult.fail(1002);
        }
        //密码加密
        String pwd = Password.slatPwd(regDto.getPassword());
        //注册
        int res = userService.reg(regDto.getUsername(), pwd);
        if(res == 1){
            return AjaxResult.success("注册成功");
        } else {
            return AjaxResult.fail();
        }
    }
    //登录
    @PostMapping("/login")
    public AjaxResult login(@RequestBody RegDto regDto){
        //参数校验
        if(!StringUtils.hasLength(regDto.getUsername()) || !StringUtils.hasLength(regDto.getPassword())){
            return AjaxResult.fail(1001);
        }
        //根据用户名查密码
        Userinfo userinfo = userService.getUserinfo(regDto.getUsername());
        if(userinfo == null){
            return AjaxResult.fail(1001);
        }
        //验证密码
        boolean login = Password.checkPwd(regDto.getPassword(), userinfo.getPassword());
        if(login){
            //生成token
            Map<String, String> map = new HashMap<>();
            map.put("id", String.valueOf(userinfo.getId()));
            map.put("username", userinfo.getUsername());
            String token = JwtUtils.createToken(map);
            // 将token存储在redis中，并设置了一天的过期时间
            redisTemplate.opsForValue().setIfAbsent("USER_LOGIN_" + userinfo.getId(), token, 1, TimeUnit.DAYS);
            return AjaxResult.success(token);
        } else {
            return AjaxResult.fail(1001);
        }
    }
    // 退出登录
    public AjaxResult logout(HttpServletRequest request){
        Integer userId = JwtUtils.getUserIdByRequest(request);
        // 检查token是否在redis中存在
        String res = redisTemplate.opsForValue().get(userId);
        if(res == null){
            return AjaxResult.success("退出成功");
        } else {
            redisTemplate.opsForValue().getAndDelete(String.valueOf(userId));
        }
        return AjaxResult.success("退出成功");
    }
}
